<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { encryptHex } from '@/utils/aesUtil'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '新增账号'
  },
  editData: {
    type: Object,
    default: () => ({})
  },
  isCurrentUser: {
    type: Boolean,
    default: false
  }
})

// 定义emits
const emit = defineEmits(['update:visible', 'confirm'])

// 表单数据
const formData = reactive({
  identity: '',
  phoneNumber: '',
  nickName: '',
  password: '',
  status: '',
  remark: ''
})

// 表单校验规则
const rules = {
  identity: [
    { required: true, message: '请选择身份', trigger: 'change' }
  ],
  phoneNumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  nickName: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  password: [
    { required: false, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20位', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 身份选项
const identityOptions = [
  { label: '超级管理员', value: 1 },
  { label: '普通管理员', value: 2 }
]

// 状态选项
const statusOptions = [
  { label: '正常', value: 0 },
  { label: '禁用', value: 1 }
]

// 表单ref
const formRef = ref()

// 是否已修改
const isModified = ref(false)

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach(key => {
    formData[key] = ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  isModified.value = false
  // 重置验证规则
  rules.password[0].required = true
}

// 监听编辑数据变化
watch(() => props.editData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    // 编辑模式，填充数据
    Object.keys(formData).forEach(key => {
      if (newData[key] !== undefined) {
        formData[key] = newData[key]
      }
    })
    // 编辑模式下密码非必填
    rules.password[0].required = false
    isModified.value = false
  } else {
    // 新增模式，清空数据
    resetForm()
    // 新增模式下密码必填
    rules.password[0].required = true
  }
}, { immediate: true, deep: true })

// 监听弹窗显示状态
watch(() => props.visible, (visible) => {
  if (!visible) {
    // 弹窗关闭时重置修改状态
    isModified.value = false
    // 确保表单也被重置
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  }
})

// 监听表单数据变化
watch(formData, () => {
  isModified.value = true
}, { deep: true })

// 确认提交
const handleConfirm = async () => {
  try {
    await formRef.value.validate()
    
    const submitData = {
      ...formData,
      identity: Number(formData.identity),
      status: Number(formData.status)
    }
    
    // 加密密码（只有在有密码时才加密）
    if (formData.password) {
      submitData.password = encryptHex(formData.password)
    } else {
      // 如果没有密码，删除密码字段
      delete submitData.password
    }
    
    // 如果是编辑模式，添加userId
    if (props.editData && props.editData.id) {
      submitData.userId = props.editData.id
    }
    
    emit('confirm', submitData)
  } catch (error) {
    ElMessage.warning("请输入正确的内容")
  }
}

// 取消操作
const handleCancel = async () => {
  if (isModified.value) {
    try {
      await ElMessageBox.confirm(
        '内容未保存，确定要关闭吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      closeDialog()
    } catch {
      // 用户取消关闭，不做任何操作
      return
    }
  } else {
    closeDialog()
  }
}

// 关闭弹窗
const closeDialog = () => {
  emit('update:visible', false)
  // 延迟重置表单，确保弹窗完全关闭后再重置
  setTimeout(() => {
    resetForm()
  }, 100)
}

// 点击遮罩层
const handleClose = async () => {
  await handleCancel()
}
</script>

<template>
     <el-dialog
     :model-value="visible"
     width="500px"
     :close-on-click-modal="false"
     :close-on-press-escape="false"
     @close="handleClose"
     class="account-dialog"
   >
     <template #header>
       <div class="dialog-header">
         <span class="dialog-title">{{ title }}</span>
       </div>
     </template>
         <el-form
       ref="formRef"
       :model="formData"
       :rules="rules"
       label-width="100px"
       label-position="right"
     >
      <el-form-item label="身份" prop="identity">
                 <el-select
           v-model="formData.identity"
           placeholder="请选择身份"
           style="width: 300px"
         >
          <el-option
            v-for="item in identityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="手机号" prop="phoneNumber">
                 <el-input
           v-model="formData.phoneNumber"
           placeholder="请输入手机号"
           maxlength="11"
           style="width: 300px"
         />
      </el-form-item>
      
             <el-form-item label="昵称" prop="nickName">
         <el-input
           v-model="formData.nickName"
           placeholder="请输入昵称"
           style="width: 300px"
         />
       </el-form-item>
       
               <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            :placeholder="editData && editData.id ? '请输入新密码（可选）' : '请输入密码'"
            style="width: 300px"
            show-password
          />
        </el-form-item>
       
               <el-form-item label="状态" prop="status">
          <el-select
            v-model="formData.status"
            placeholder="请选择状态"
            style="width: 300px"
            :disabled="isCurrentUser"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="isCurrentUser && item.value === 1"
            />
          </el-select>
        </el-form-item>
      
      <el-form-item label="备注" prop="remark">
                 <el-input
           v-model="formData.remark"
           type="textarea"
           placeholder="请输入备注（可选）"
           :rows="3"
           style="width: 300px"
         />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          {{ editData && editData.id ? '更新' : '确定' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.account-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 20px 0;
    border-bottom: 1px solid #f0f0f0;
  }
  
  :deep(.el-dialog__body) {
    padding: 30px 20px;
  }
  
  :deep(.el-dialog__footer) {
    padding: 0 20px 20px;
    border-top: 1px solid #f0f0f0;
  }
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-title {
  font-size: 18px;
  font-weight: normal;
  color: #333;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-textarea__inner) {
  resize: vertical;
}
</style> 